import request from "../../request/http";

// pages/cart/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
  cart:[],

  totalPrice:0,
  totalNum:0,

  },
 
  onShow(){
    const cart=wx.getStorageSync('cart')||[];
    cart.filter(item=>item.checked)
     //合计
     let totalPrice=0;
     //总数量
     let totalNum=0;
     cart.forEach(item=>{
         totalPrice+=item.num*item.goods_price;
         totalNum+=item.num
     })
     this.setData({
       cart,totalNum,totalPrice
     })  
  },

//点击支付 
async handlePaymentBtn(){
  const token =wx.getStorageSync('token')
  if(!token){
    wx.navigateTo({
      url: '/pages/auth/index',
    })
  }
  let {totalPrice,cart}=this.data
  let goods=[];
  cart.forEach(item=>{
      goods.push({"goods_id":item.goods_id,"goods_number":item.num,"goods_price":item.goods_price}) 
  })
  let res=await request({url:'my/orders/create',method:'post',data:{"order_price":totalPrice,"goods":goods}
})
if(res.meta.status===200){
  let order_number=res.message.order_number
  let res1=await request({url:'my/orders/req_unifiedorder',method:'post',data:{"order_number":order_number}})
  console.log('预支付订单',res1);
  if(res1.meta.status===200){
    let {pay}=res1.message
    console.log('pay',pay);
    //4.微信的支付窗口
   
    wx.requestPayment({
      ...pay,
      success (res) { 
        console.log('弹出窗口成功',res);  
      },
      fail (err) {
        console.log('失败',err); 
       }
    })

}

  //5.查询订单支付状态，提醒用户是否支付成功
  let res2=await request({url:'my/orders/chkOrder',method:'post',data:{"order_number":order_number}})
  console.log('是否支付',res2);
  if(res2.meta.status===200){
    wx.showToast({
      title: '支付成功',
    })
    wx.navigateTo({
      url: '/pages/order/index',
    })
 } 
 else{
   wx.showToast({
     title: '支付失败',
   })
 } 

}

}, 
  onLoad(options) {
   
  },
  // 获取收货地址
  handleChooseAddress(){
    wx.chooseAddress({
      success: (result1) => {
        console.log(result1);
      }
    }) 
  },

  
     
 
})